package com.peng.binarysearchnorecursion.practice;

/**
 * 练习 二分查找 敲代码
 *
 * @author sp
 */
public class BinarySearchNoRecurPractice {

    public static void main(String[] args) {
        int[] arr = {1, 3, 8, 10, 11, 67, 100};
        int index = binarySearch(arr, 100);
        System.out.println("index=" + index);

        index = binarySearch(arr, 1000);
        System.out.println("index=" + index);
    }


    /**
     * 第一种写法 采用while循环实现二分查找
     *
     * @param arr    查询的数组
     * @param target 待查找的值
     * @return int
     */
    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        // 开始循环，条件为 left，right
        while (left <= right) {

            //二分查找 确定区间中点位置index
            int mid = (left + right) / 2;
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] > target) {
                //向左边边查找
                right = right - 1;
            } else {
                //向右边查找
                left = left + 1;
            }

        }
        //没有找到
        return -1;
    }
}
